package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class AuthorityController implements UserDetailsService {
    @Reference
    UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User userDB= userService.login(username);
        UserDetails userDetails=null;
        if (userDB!=null){
            Set<Role> roles = userDB.getRoles();
            List<GrantedAuthority> authorities=new ArrayList<>();
            for (Role role : roles) {
                authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
                Set<Permission> permissions = role.getPermissions();
                for (Permission permission : permissions) {
                    authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
                }
            }
            userDetails=new org.springframework.security.core.userdetails.User(userDB.getUsername(), userDB.getPassword(), authorities);
        }

        return userDetails;
    }
}
